package com.wise.site.model;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.wise.site.R;
import com.wise.site.utils.Constanct;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class GoogleMapBrowserActivity extends Activity implements View.OnClickListener {
	
	
	private static final int LOADINGSUCCESS = 1000;
	private static final int LOADINGFAILE = LOADINGSUCCESS + 1;
	private WebView mWebView;
	private String bestProvider;
	private LocationManager mLocationManager;
	private double locLatLon[];
	private double latLon[];
	private Handler handler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_map_browser_activity);
		mWebView = (WebView) findViewById(R.id.webView);
		
		
		findViewById(R.id.title_back).setOnClickListener(this);
		findViewById(R.id.search_path).setOnClickListener(this);
		
		mWebView.setWebChromeClient(new MyWebChromeClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		Toast.makeText(this, "正在加载地图", Toast.LENGTH_SHORT).show();
		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		bestProvider = mLocationManager.getBestProvider(new Criteria(), true);   //设置查询条件  
		
		
		loadMap();
		
		//Location loc = mLocationManager.getLastKnownLocation("network");      //获取用户位置信息
		/*Location loc = mLocationManager.getLastKnownLocation(bestProvider);
		if(loc != null){
			
		}
		new Thread(){
			public void run() {
				JSONObject jsonObject = getLocationInfo(getIntent().getStringExtra(Constanct.INTENT_ADDR));
				if(jsonObject != null){
					mHandler.sendMessage(mHandler.obtainMessage(LOADINGSUCCESS, jsonObject));
				}else{
					mHandler.sendEmptyMessage(LOADINGFAILE);
				}
			};
		}.start();*/
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}





	private void loadMap() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String addr = getIntent().getStringExtra(Constanct.INTENT_ADDR);
				if(addr != null){
					JSONObject jsonObject = getLocationInfo(addr);
					latLon = getLatLon(jsonObject);
				}
				//JSONObject jsonObject = getLocationInfo("深圳上梅林");
				if(latLon[0] == 0 && latLon[1] == 0){
					handler.post(new Runnable() {
						public void run() {
							Toast.makeText(GoogleMapBrowserActivity.this, "不能找到商铺地址", Toast.LENGTH_SHORT).show();
						}
					});
				}
				Location loc = null;
				if(bestProvider != null){
					loc = mLocationManager.getLastKnownLocation(bestProvider);
				}
				if (loc != null) {
					locLatLon = new double[] { loc.getLatitude(),
							loc.getLongitude() };
					mWebView.addJavascriptInterface(new Object() {
						public double getLat() {
							if(latLon[0] == 0){
								return locLatLon[0];
							}
							return latLon[0];
						}

						public double getLon() {
							if(latLon[1] == 0){
								return locLatLon[1];
							}
							return latLon[1];
						}

						public double getLocLat() {
							return locLatLon[0];
						}

						public double getLocLon() {
							return locLatLon[1];
						}

						public void printStr(String str) {
							System.out.println(str);
						}
						
						public void showError(){
							handler.post(new Runnable() {
								public void run() {
									Toast.makeText(GoogleMapBrowserActivity.this, "定位失败",
											Toast.LENGTH_SHORT).show();
								}
							});
						}
 
						public void hideDialg() {

						}
					}, "callback");
//					mWebView.loadUrl("file:///android_asset/map.html");
				} else {

				}
				mWebView.loadUrl("file:///android_asset/map.html");
			}
		}).start();
	}
	
	
	
	
	
	private JSONObject getLocationInfo(String addr){
		StringBuilder sb = new StringBuilder();
		JSONObject jsonObject = null;// = new JSONObject();
		addr = addr.replaceAll(" ", "%20");
		try {
			HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + addr + "&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				sb.append((char) b);
			}
			jsonObject = new JSONObject(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	
	private double[] getLatLon(JSONObject jsonObject){
		double latLon[] = new double[2];
		try {
			latLon [0] = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
			latLon [1] = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return latLon;
	}
	
	private GeoPoint getLatLong(JSONObject jsonObject){
		Double lon = new Double(0);
		Double lat = new Double(0);
		try {
			lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
			lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
	}
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int what = msg.what;
			switch(what){
			case LOADINGSUCCESS:
				break;
			case LOADINGFAILE:
				Toast.makeText(GoogleMapBrowserActivity.this, "定位失败", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	
	private class MyWebChromeClient extends WebChromeClient{

		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result) {
			Toast.makeText(GoogleMapBrowserActivity.this, message, Toast.LENGTH_SHORT).show();
			return true;
		}
		
	}
	
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		int id = view.getId();
		switch(id){
		case R.id.title_back:
			finish();
			break;
		case R.id.search_path:
			showDialog();
			break;
		}
	}
	
	
	private void showDialog(){
		
		if(locLatLon == null){
			return;
		}
		
		if(latLon == null){
			Toast.makeText(this, "缺少起点或终点", Toast.LENGTH_SHORT).show();
			return;
		}
		Resources resources = getResources();
		final CharSequence[] items = {resources.getString(R.string.bus), resources.getString(R.string.walk), resources.getString(R.string.driving)}; 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_access); 
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) { 
                StringBuilder params = new StringBuilder().append("&dirflg="); 
                switch (item) {
                case 0: 
                    params.append("r"); 
                    break; 
                case 1: 
                    params.append("w"); 
                    break; 
                case 2: 
                    params.append("d"); 
                    break; 
                default: 
                    break; 
                }
                getMap(params.toString());
            } 
        }); 

        AlertDialog alert = builder.create(); 
        alert.show();
	}
	
	private void getMap(String params) {
		String path = "http://ditu.google.cn/maps?f=d&source=s_d&saddr=" 
				+ locLatLon[0] + "," + locLatLon[1]
				+ "&daddr=" + latLon[0] + "," + latLon[1]
				+ "&hl=zh&t=m&" + params;
		Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(path)); 
		try {
	        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 
	        i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); 
	        startActivity(i);
		} catch (Exception e) {
			startActivity(i);
		}
	}

}
